<?php

/**
 * Description of PublicController
 *
 * @author Poh Nean
 */
class PublicController extends Controller
{

	public $layout = '/public/layout';

	/**
	 * @var Agency the agency
	 */
	public $agency;

	public function filters()
	{
		return CMap::mergeArray(parent::filters(), array(
					'agencyContext'
		));
	}

	public function filterAgencyContext(CFilterChain $filterChain)
	{
		if (isset($_GET['agency_id'])) {
			$this->agency = Agency::model()->findByAttributes(array('id' => $_GET['agency_id']));
		}

		// check module
		if ($this->agency !== null) {
			if ($this->agency->checkModuleAccess('Propsage.TicketManagement') === false) {
				throw new PsPageNotFoundException();
			}
		} else {
			throw new PsPageNotFoundException();
		}

		$filterChain->run();
	}

	/**
	 * Site controller access rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow all users
				'users' => array('*'),
			),
		);
	}

	public function actionIndex()
	{
		$ticket = new Ticket();

		if (isset($_POST['Ticket'])) {
			$userTicket = Ticket::model()->findByAttributes(array(
				'email' => $_POST['Ticket']['email'],
				'ticket_number' => $_POST['Ticket']['ticket_number']
			));

			if ($userTicket === null) {
				PsSystemMessage::add('Ticket not found.', 'error', false);
			} else {
				$this->redirect(array('public/list', 'ticket_number' => $userTicket->ticket_number, 'email' => $userTicket->email, 'agency_id' => $this->agency->id));
			}
		}

		$data = array();
		$data['ticket'] = $ticket;
		$this->render('index', $data);
	}

	public function actionOpen()
	{
		$ticket = new Ticket;

		if (isset($_POST['Ticket'])) {
			$ticket->agency_id = $this->agency->id;
			$ticket->attributes = $_POST['Ticket'];
			$ticket->source = 'Web';

			$isValid = $ticket->validate();
			if ($isValid) {
				$tx = Yii::app()->db->beginTransaction();

				try {
					$ticket->save(false);

					$ticketStatus = new TicketStatus;
					$ticketStatus->type = 'Open';
					$ticketStatus->ticket_id = $ticket->id;
					$ticketStatus->status_time = new CDbExpression('UTC_TIMESTAMP()');
					$ticketStatus->save(false);

					$tx->commit();
					
					$success = $ticket->sendNotificationEmail(Ticket::NOTIFICATION_TYPE_NEW);

					PsSystemMessage::add('Ticket #' . $ticket->ticket_number . ' submitted.', 'success', false);
					$this->redirect(array('public/index', 'agency_id' => $this->agency->id));
				} catch (CDbException $e) {
					$tx->rollback();
//					dump($e);
				}
			} else {
//				dump($ticket->getErrors());
			}
		}

		$data = array();
		$data['ticket'] = $ticket;
		$this->render('create', $data);
	}

	public function actionUpdate($ticket_number, $email)
	{
		$ticket = $this->loadTicket($ticket_number, $email);

		if (isset($_POST['Ticket'])) {
			$ticket->attributes = $_POST['Ticket'];
			$isValid = $ticket->validate();

			if ($isValid) {
				$tx = Yii::app()->db->beginTransaction();

				try {
					$ticket->save(false);

					$tx->commit();

					$this->redirect(array('public/index', 'agency_id' => $this->agency->id));
					PsSystemMessage::add('Ticket updated.', 'success');
				} catch (CDbException $e) {
					$tx->rollback();
				}
			} else {
				
			}
		}

		$data = array();
		$data['ticket'] = $ticket;
		$this->render('update', $data);
	}

	public function actionList($ticket_number, $email)
	{
		$userTicket = $this->loadTicket($ticket_number, $email);

		$ticket = new Ticket('search');
		$ticket->unsetAttributes();
		$ticket->email = $userTicket->email;
		$ticket->agency_id = $userTicket->agency_id;
		$ticket->current_status = $ticket_status;

		if (isset($_GET['Ticket'])) {
			$ticket->attributes = $_GET['Ticket'];
			$ticket->agency_id = $userTicket->agency_id;
		}

		$data = array();
		$data['ticket'] = $ticket;
		$data['ticketStatusTypes'] = TicketStatusType::model()->findAll(array('order' => 'is_closing_status ASC'));

		$this->render('list', $data);
	}

	public function actionView($ticket_number, $email)
	{
		$ticket = $this->loadTicket($ticket_number, $email);

		$newTicketResponse = new TicketResponse;

		if (isset($_POST['TicketResponse'])) {
			$newTicketResponse->ticket_id = $ticket->id;
			$newTicketResponse->agency_id = $ticket->agency_id;
			$newTicketResponse->responded_by_email = $email;

			$newTicketResponse->response_time = new CDbExpression('UTC_TIMESTAMP()');
			$newTicketResponse->attributes = $_POST['TicketResponse'];

			if ($newTicketResponse->validate()) {
				$tx = Yii::app()->db->beginTransaction();
				try {
					if (isset($_POST['Ticket'])) {
						$oldStatus = $ticket->current_status;

						if ($_POST['alsoChangeStatus'] == 1) {
							$ticket->current_status = $_POST['Ticket']['current_status'];
							if ($ticket->current_status != $oldStatus) {
								$ticketStatus = new TicketStatus;
								$ticketStatus->type = $ticket->current_status;
								$ticketStatus->ticket_id = $ticket->id;
								$ticketStatus->status_time = new CDbExpression('UTC_TIMESTAMP()');
								$ticketStatus->save(false);
							}

							$ticket->save(false);
						}
					}
					
					$newTicketResponse->save(false);
					
					$ticket->sendNotificationEmail(Ticket::NOTIFICATION_TYPE_UPDATED, array('response' => $newTicketResponse->message));

					$tx->commit();

					$this->refresh();
				} catch (CDbException $e) {
					$tx->rollback();
				}
			}
		}

		$data = array();
		$data['ticket'] = $ticket;
		$data['newTicketResponse'] = $newTicketResponse;
		$this->render('view', $data);
	}

	/**
	 * @param string $ticket_number
	 * @return Ticket
	 * @throws PsPageNotFoundException
	 */
	public function loadTicket($ticket_number, $email)
	{
		$ticket = Ticket::model()->findByAttributes(array(
			'ticket_number' => $ticket_number,
			'email' => $email,
			'agency_id' => $this->agency->id
		));

		if ($ticket === null) {
			throw new PsPageNotFoundException();
		}

		return $ticket;
	}

}

?>
